package com.tdw.eurekaclient.controller;

import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tdw.eurekaclient.dto.UserInfo;

@RestController
@RequestMapping(value="/hystrix")
public class HystrixController {
	private static final Logger log = LoggerFactory.getLogger(HystrixController.class);
	@Autowired
	private DiscoveryClient client;
	
	
	@RequestMapping(value="/test")
	public String test(HttpServletRequest request, HttpServletResponse response){
		ServiceInstance instance = client.getLocalServiceInstance();
		log.info("####host={},port={},serviceId={}",instance.getHost(),instance.getPort(),instance.getServiceId());
		
		Map<String, String[]> map = request.getParameterMap();
		for(Entry<String, String[]> entry : map.entrySet()){
			log.info("parm key={},parm value={}",entry.getKey(),entry.getValue());
		}
		if("err".equals(request.getParameter("error"))){
			throw new RuntimeException("错误编码");
		}else if("404".equals(request.getParameter("http_status"))){
			throw new RuntimeException("错误编码");
		}else if("timeout".equals(request.getParameter("http_status"))){
			for(int i=0;i<10;i++){
				try {
					Thread.sleep(1 * 1000);
				} catch (InterruptedException e) {
					log.error("失败",e);
				}
				log.info("===========sleep {}============",i);
			}
			return "ok , sleep 10s";
		}
		return "ok";
	}
	
	
	
	@RequestMapping(value="/getUserById")
	public UserInfo getUserById(HttpServletRequest request, HttpServletResponse response){
		UserInfo user = new UserInfo();
		user.setId(request.getParameter("id"));
		user.setAddress("湖南省长沙市雨花区");
		user.setAge(Math.abs(new Random().nextInt(100)));
		user.setSex('0');
		return user;
	}
	
	
	
	
	
}
